import { Slots } from "vue";
import { DynamicTableProps } from "../dynamic-table";
import type { TablePageProps } from "@layui/layui-vue/types/component/table/TablePage.vue";
import { LayTable } from "@layui/layui-vue";
import { Recordable } from "@layui/layui-vue/types/types/public";
import { omit } from "lodash-es";

export type TableState = ReturnType<typeof useTableState>;
export type UseTableStateParams = {
  props: DynamicTableProps;
  slots: Slots;
};
export type Pagination = NonNullable<TablePageProps>;
export const useTableState = ({ props, slots }: UseTableStateParams) => {
  /** 表格实例 */
  const tableRef = ref<InstanceType<typeof LayTable>>();
  /** 编辑表格的表单实例 */
  const editTableFormRef = ref<any>();
  /** 表格数据 */
  const tableData = ref<any[]>([]);
  /** 内部属性 */
  const innerPropsRef = ref<Partial<DynamicTableProps>>();
  /** 表格加载 */
  const loadingRef = ref<boolean>(!!props.loading);
  /**表格默认分页 */
  const defaultPagination = ref<Partial<TablePageProps>>({
    current: 1,
    limit: props.defaultPageSize || 10,
    total: 0,
  });
  /***
   * 选中行
   */
  const selectedKeys = ref([]);
  const selectedKey = ref("");
  /** 分页配置参数 */
  const page = ref<Pagination>();
  if (props.enablePaging) {
    const limits = props.pageCountList?.split(",").map((_) => Number(_)) || [
      10, 20, 30, 40, 50,
    ];
    page.value = {
      limits: limits,
      current: 1,
      total: 0,
      limit: Number(props.defaultPageSize) || limits[0],
    };
  } else {
    page.value = undefined;
  }
  const getProps = computed(() => {
    return { ...props, ...unref(innerPropsRef) };
  });
  const getBindValues = computed(() => {
    const props = unref(getProps);

    let propsData: Recordable = {
      ...props,
      rowKey: props.rowKey ?? "id",
      loading: props.loading ?? unref(loadingRef),
      page: unref(page),
    };
    propsData = omit(propsData, ["class", "onChange", "columns"]);
    return propsData;
  });
  // 如果外界设置了dataSource，那就直接用外界提供的数据
  watch(
    () => props.dataSource,
    (val) => {
      if (val) {
        tableData.value = val.map((_) => _);
        page.value!.total = tableData.value.length;
      }
    },
    {
      immediate: true,
      deep: true,
    },
  );
  watch(
    () => props.columns,
    (val) => {
      if (val) {
        innerPropsRef.value = {
          ...innerPropsRef.value,
          columns: val,
        };
      }
    },
    {
      immediate: true,
      deep: true,
    },
  );
  return {
    selectedKeys,
    selectedKey,
    tableRef,
    editTableFormRef,
    tableData,
    innerPropsRef,
    loadingRef,
    page,
    getProps,
    getBindValues,
    defaultPagination,
  };
};
